package controllers;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXTextField;
import controllers.cell.CommodityCellRenderer;
import database.dao.Impl.CommodityDaoImpl;
import database.dao.Impl.InvoiceDaoImpl;
import database.dao.Impl.OrderRecordDaoImpl;
import entity.*;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import services.SystemContext;

import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @ClassName SystemViewController
 * @Description TODO
 * @Author lzq
 * @Date 2021/6/15 19:31
 */
public class SystemViewController implements Initializable {

    public AnchorPane thePane;
    public Label textBtn1;
    public Label textBtn2;
    public Label userTypetext;
    public Button closeBtn;
    public Button minBtn;
    public AnchorPane MainViewPane;
    public JFXComboBox sortComboBox;
    public JFXComboBox classifyComboBox;
    public JFXButton PostOrderBtn;
    public JFXButton AddCommodityBtn;
    public ListView CommodityList;
    public JFXTextField commodityField;
    public Label SumLabel;
    public TableView OrderTableView;
    public TableView OtherTable;
    public JFXButton selectBtn;
    public ToolBar toolbar;
    public Label TitleText;

    private double xOffset;
    private double yOffset;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Stage stage= ViewManager.STAGE.get("primaryStage");
        ViewManager.CONTROLLER.put("SystemViewController",this);
        System.out.println(stage.getTitle());
        if(stage.getTitle().equals("CustomerView")){
            userTypetext.setText("买家端");
            textBtn1.setText("我的订单");
            textBtn2.setText("订购商品");
            if(AddCommodityBtn!=null)
                AddCommodityBtn.setVisible(false);
        }

        //拖放功能
        thePane.setOnMousePressed(event -> {
            xOffset = stage.getX() - event.getScreenX();
            yOffset = stage.getY() - event.getScreenY();
            thePane.setCursor(Cursor.CLOSED_HAND);
        });

        thePane.setOnMouseDragged(event -> {
            stage.setX(event.getScreenX() + xOffset);
            stage.setY(event.getScreenY() + yOffset);
        });
        thePane.setOnMouseReleased(event -> {
            thePane.setCursor(Cursor.DEFAULT);
        });


        if(CommodityList!=null){
            if(SystemContext.getInstance().getIsCustomer()){
                SumLabel.setText("0.00");
            }else{
                PostOrderBtn.setVisible(false);
                SumLabel.setVisible(false);
            }
            CommodityList.setItems(SystemContext.getInstance().getCommodityObservableList());
            CommodityList.setCellFactory(new CommodityCellRenderer());

            initComboBox();
        }

        if(OrderTableView!=null){
            TitleText.setText("订单记录");
            if(SystemContext.getInstance().getIsCustomer()){

                System.out.println("Customer");
                TableColumn id=new TableColumn("  订单id号   ");
                TableColumn name=new TableColumn(" 商品名称 ");
                TableColumn quantity=new TableColumn("   购买商品数量   ");
                TableColumn status=new TableColumn("    订单状态    ");
                TableColumn order_data=new TableColumn("  购买日期   ");

                TableColumn invoice_id=new TableColumn("购买记录id");
                TableColumn total_price=new TableColumn("总价 ");
                TableColumn invoice_date=new TableColumn(" 购买日期");

                invoice_id.setCellValueFactory(
                        new PropertyValueFactory<InvoiceRecord,String>("invoice_id"));
                total_price.setCellValueFactory(
                        new PropertyValueFactory<InvoiceRecord,String>("total_price"));
                invoice_date.setCellValueFactory(
                        new PropertyValueFactory<InvoiceRecord,String>("order_date"));

                OtherTable.getColumns().addAll(invoice_id,total_price,invoice_date);
                OtherTable.setItems(SystemContext.getInstance().getInvoiceRecordObservableList());


                id.setCellValueFactory(
                        new PropertyValueFactory<>("order_id"));
                name.setCellValueFactory(
                        new PropertyValueFactory<>("name"));
                quantity.setCellValueFactory(
                        new PropertyValueFactory<>("quantity"));
                status.setCellValueFactory(
                        new PropertyValueFactory<>("status"));
                order_data.setCellValueFactory(
                        new PropertyValueFactory<>("order_date"));

                OrderTableView.getColumns().addAll(id, name, quantity, status,order_data);
                OrderTableView.setItems(SystemContext.getInstance().getUserOrderObservableList());

            }else{

                OrderTableView.setMinHeight(700);
                toolbar.setVisible(false);
                OtherTable.setVisible(true);

                System.out.println("Business");
                TableColumn id=new TableColumn("   order_id   ");
                TableColumn username=new TableColumn(" username ");
                TableColumn userAddress=new TableColumn(" userAddress ");
                TableColumn name=new TableColumn(" name ");
                TableColumn quantity=new TableColumn("   quantity   ");
                TableColumn status=new TableColumn("    status    ");
                TableColumn order_data=new TableColumn("     order_data      ");
                id.setCellValueFactory(
                        new PropertyValueFactory<>("order_id"));
                username.setCellValueFactory(
                        new PropertyValueFactory<BusinessOrder,String>("userName"));
                userAddress.setCellValueFactory(
                        new PropertyValueFactory<>("userAddress"));
                name.setCellValueFactory(
                        new PropertyValueFactory<>("name"));
                quantity.setCellValueFactory(
                        new PropertyValueFactory<>("quantity"));
                status.setCellValueFactory(
                        new PropertyValueFactory<BusinessOrder,String>("status"));

                OrderTableView.setEditable(true);
                status.setEditable(true);

                order_data.setCellValueFactory(
                        new PropertyValueFactory<>("order_date"));
                OrderTableView.getColumns().addAll(id, username, userAddress,name,quantity, status,order_data);
                OrderTableView.setItems(SystemContext.getInstance().getBusinessOrderObservableList());

                status.setCellFactory(TextFieldTableCell.forTableColumn());
                status.setOnEditCommit(
                        new EventHandler<TableColumn.CellEditEvent<BusinessOrder, String>>() {
                            @Override
                            public void handle(TableColumn.CellEditEvent<BusinessOrder, String> t) {
                                ((BusinessOrder) t.getTableView().getItems().get(
                                        t.getTablePosition().getRow())
                                ).setStatus(t.getNewValue());
                                OrderRecordDaoImpl orderRecordDao=new OrderRecordDaoImpl();
                                orderRecordDao.updateOrderStatus(((Integer)((BusinessOrder) t.getTableView().getItems().get(
                                        t.getTablePosition().getRow())
                                ).getOrder_id()).toString(),t.getNewValue());
                            }
                        }
                );
            }
        }
    }

    /***
     * @Title:initComboBox
     * @Description:在打开商品面板后，初始化sortComboBox，classifyComboBox
     * @param
     * @return void
     * @Author: lzq
     */
    public void initComboBox(){

        sortComboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Label>() {
            @Override
            public void changed(ObservableValue<? extends Label> observable, Label oldValue, Label newValue) {
                newValue=newValue==null?oldValue:newValue;
                if(newValue==null){
                    sortListDesc();
                    return;
                }

                System.out.println(newValue.getText());
                if(newValue.getText().equals("价格升序"))
                    sortListDesc();
                else if(newValue.getText().equals("价格降序"))
                    sortListAsc();
            }
        });

        classifyComboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Label>() {
            @Override
            public void changed(ObservableValue<? extends Label> observable, Label oldValue, Label newValue) {
                Label value;
                value=newValue==null?oldValue:newValue;
                if(value==null)return;

                System.out.println(value.getText());
                SystemContext.getInstance().getCommodityObservableList().removeIf(commodity -> !commodity.getCommodity_type().equals(value.getText()));
                CommodityList.refresh();

                if (SystemContext.getInstance().getCommodityObservableList().size() == 0) {
                    SystemContext.getInstance().refreshCommodityList();
                    SystemContext.getInstance().getCommodityObservableList().removeIf(commodity -> !commodity.getCommodity_type().equals(value.getText()));
                    CommodityList.refresh();
                }
            }
        });
    }

    /***
     * @Title:minAction
     * @Description:最小化窗口
     * @param actionEvent
     * @return void
     * @Author: lzq
     */
    public void minAction(ActionEvent actionEvent) {
        ViewManager.STAGE.get("primaryStage").setIconified(true);
    }
    /***
     * @Title:closeAction
     * @Description:关闭按钮
     * @param actionEvent
     * @return void
     * @Author: lzq
     */

    public void closeAction(ActionEvent actionEvent) {
        Platform.exit();
        System.exit(0);
    }

    /***
     * @Title:OrderBtnAction
     * @Description:打开订单面板
     * @param actionEvent
     * @return void
     * @Author: lzq
     */
    public void OrderBtnAction(ActionEvent actionEvent) {
        Stage stage= ViewManager.STAGE.get("primaryStage");
        Parent OrderParent=null;

        SystemContext.getInstance().refreshOrderList();
        if(SystemContext.getInstance().getIsCustomer())
            SystemContext.getInstance().refreshInvoiceList();

        try {
            OrderParent = FXMLLoader.load(getClass().getResource("/views/InvoiceView.fxml"));

        } catch (IOException e) {
            e.printStackTrace();
        }
        stage.getScene().setRoot(OrderParent);
    }


    /***
     * @Title:CommodityBtnAction
     * @Description:打开商品面板（商家端：查找对应商家id的所有商品，可增删改查）（买家端：查找所有商品，可购买）
     * @param actionEvent
     * @return void
     * @Author: lzq
     */
    public void CommodityBtnAction(ActionEvent actionEvent) {
        Stage stage= ViewManager.STAGE.get("primaryStage");
        Parent CommodityParent=null;
        CommodityParent=ViewManager.Parents.get("CommodityParent");
        if(CommodityParent==null) {
            try {
                SystemContext.getInstance().refreshCommodityList();
                CommodityParent = FXMLLoader.load(getClass().getResource("/views/CommodityView.fxml"));

                ViewManager.Parents.put("CommodityParent",CommodityParent);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        SumLabel=(Label) ViewManager.Parents.get("CommodityParent").lookup("#SumLabel");
        stage.getScene().setRoot(CommodityParent);
    }


    /***
     * @Title:SelectCommodityAct
     * @Description:查找商品，根据搜索框信息模糊查询
     * @param actionEvent
     * @return void
     * @Author: lzq
     */
    public void SelectCommodityAct(ActionEvent actionEvent) {
        if(!commodityField.getText().equals("")){
            System.out.println(commodityField.getText());
            CommodityDaoImpl commodityDao=new CommodityDaoImpl();

            String id;
            if(SystemContext.getInstance().getIsCustomer()){
                id=null;
            }else
                id=SystemContext.getInstance().getId();

            List<Commodity>list=commodityDao.SelectCommodity(id,commodityField.getText());

            SystemContext.getInstance().setCommodityObservableList(FXCollections.observableList(list));

        }else {
            for (JFXComboBox jfxComboBox : Arrays.asList(classifyComboBox, sortComboBox)) {
                jfxComboBox.getSelectionModel().select(-1);
            }

            SystemContext.getInstance().refreshCommodityList();

            SystemViewController controller=(SystemViewController)(ViewManager.CONTROLLER.get("SystemViewController"));
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    if(controller!=null&&controller.CommodityList!=null)
                        controller.CommodityList.refresh();
                }
            });
        }
        sortListAsc();
    }

    /***
     * @Title:PostOrderAction
     * @Description:订购所选择的商品，产生一个订单号与多个订单记录，清空面板购买情况
     * @param actionEvent
     * @return void
     * @Author: lzq
     */
    public void PostOrderAction(ActionEvent actionEvent) {

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Tip!");
        alert.setHeaderText("购买成功");
        alert.setContentText("你共选购"+SumLabel.getText()+"元\n您可选择查看订单或者继续选购");
        alert.showAndWait();

        Invoice invoice=new Invoice(SystemContext.getInstance().getId(),Float.parseFloat(SumLabel.getText()));
        InvoiceDaoImpl invoiceDao=new InvoiceDaoImpl();
        String invoice_id=invoiceDao.addInvoice(invoice);
        for(Commodity value:SystemContext.getInstance().getBuyList().values()){
            OrderRecordDaoImpl orderRecordDao=new OrderRecordDaoImpl();
            orderRecordDao.addOrderRecord(new OrderRecord(invoice_id,value.getCommodity_id().toString(),value.getBuyNumber()));
        }
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                SystemContext.getInstance().refreshCommodityList();
                SumLabel.setText("0.00");
                SystemContext.getInstance().getBuyList().clear();
                CommodityList.refresh();
            }
        });

    }

    /***
     * @Title:AddCommodityAct
     * @Description:打开商品增添界面
     * @param actionEvent
     * @return void
     * @Author: lzq
     */
    public void AddCommodityAct(ActionEvent actionEvent) {
        Stage AddCommodityStage=ViewManager.STAGE.get("AddCommodityStage");
        if(AddCommodityStage==null) {
            AddCommodityStage = new Stage();
            ViewManager.STAGE.put("AddCommodityStage", AddCommodityStage);
            Parent root;
            try {
                root = FXMLLoader.load(getClass().getResource("/views/AddCommodityWindow.fxml"));
                AddCommodityStage.setScene(new Scene(root));
                AddCommodityStage.initStyle(StageStyle.UNDECORATED);
                AddCommodityStage.initModality(Modality.APPLICATION_MODAL);
                AddCommodityStage.show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            AddCommodityStage.show();
        }
    }

    /***
     * @Title:sortListAsc
     * @Description:对商品列表进行排序（按价格递增）
     * @param
     * @return void
     * @Author: lzq
     */
    public void sortListAsc(){
        SortedList<Commodity> sl=SystemContext.getInstance().getCommodityObservableList().sorted(new Comparator<Commodity>() {
            @Override
            public int compare(Commodity c1, Commodity c2) {
                float a=c1.getPrice();
                float b=c2.getPrice();
                return (int) (b-a);
            }
        });
        CommodityList.setItems(sl);
    }

    /***
     * @Title:sortListDesc
     * @Description:对商品进行排序（按照价格递减）
     * @param
     * @return void
     * @Author: lzq
     */
    public void sortListDesc(){
        SortedList<Commodity> sl=SystemContext.getInstance().getCommodityObservableList().sorted(new Comparator<Commodity>() {
            @Override
            public int compare(Commodity c1, Commodity c2) {
                float a=c1.getPrice();
                float b=c2.getPrice();
                return (int) (a-b);
            }
        });
        CommodityList.setItems(sl);
    }


    public void OpenUserInfo(MouseEvent mouseEvent) {
        Stage UserInfoStage=null;
        UserInfoStage=ViewManager.STAGE.get("UserInfoStage");
        if(UserInfoStage==null){
            UserInfoStage = new Stage();
            ViewManager.STAGE.put("UserInfoStage", UserInfoStage);
            Parent root;
            try {
                root = FXMLLoader.load(getClass().getResource("/views/UserInfoView.fxml"));
                UserInfoStage.setScene(new Scene(root));
                UserInfoStage.initStyle(StageStyle.UNDECORATED);
                UserInfoStage.initModality(Modality.APPLICATION_MODAL);
                UserInfoStage.show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            UserInfoStage.show();
        }

    }

    public void refeshAct(ActionEvent actionEvent) {
        SystemContext.getInstance().refreshOrderList();
    }

    public void select(ActionEvent actionEvent) {

    }
}
